package cn.service;

import cn.dto.Query;
import cn.entity.*;
import cn.mapper.*;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class AdminService{
    final String imgSaveDir = "uploadImage";

    //学术活动
    @Autowired
    private AcademicActivityMapper academicActivityMapper;
    //学术奖励
    @Autowired
    private AcademicAwardsMapper academicAwardsMapper;
    //轮播图
    @Autowired
    private BannerMapper bannerMapper;
    //联系我们
    @Autowired
    private ContactMapper contactMapper;
    //合作研究
    @Autowired
    private CooperationMapper cooperationMapper;
    //课题组简介
    @Autowired
    private IntroductionMapper introductionMapper;
    //实验设备
    @Autowired
    private MachineMapper machineMapper;
    //团队成员
    @Autowired
    private MemberMapper memberMapper;
    //团队成员信息
    @Autowired
    private MemberMsgMapper memberMsgMapper;
    //组内动态
    @Autowired
    private NewsMapper newsMapper;
    //论文
    @Autowired
    private PaperMapper paperMapper;
    //研究内容
    @Autowired
    private ResearchMapper researchMapper;
    //子菜单
    @Autowired
    private SubMenuMapper subMenuMapper;



    private String saveFile(String path, MultipartFile file) throws IOException {
        File dir = new File(path);
        if(!dir.exists()){
            dir.mkdir();
        }
        String imgName = UUID.randomUUID().toString()+file.getOriginalFilename();
        File upload = new File(dir,imgName);

        FileUtils.copyInputStreamToFile(file.getInputStream(),upload);
        return imgName;
    }

    private void deleteFile(String oldFilePath) {
        if(oldFilePath != null && oldFilePath.length() > 0){
            File file = new File(oldFilePath);
            if(file.exists()){
                file.delete();
            }
        }
    }


    public int login(String username,String password) {
        if("admin".equals(username) && "admin".equals(password)){
            return 1;
        }
        return -1;
    }


    public List<Banner> selectBannerPage(Query query) {
        query.setOffset();
        return bannerMapper.selectBannerList(query);
    }

    public int totalBannerNum() {
        return bannerMapper.totalNum();
    }

    public int saveBanner(String savePath, MultipartFile banner) throws IOException {
        String path = File.separator+imgSaveDir+File.separator+saveFile(savePath+File.separator+imgSaveDir,banner);
        Banner b = new Banner();
        b.setBanner(path);
        return bannerMapper.insertSelective(b);
    }

    public int updateBanner(String savePath, MultipartFile banner, Integer id) throws IOException {
        Banner b = bannerMapper.selectByPrimaryKey(id);
        String oldFilePath = savePath+b.getBanner();
        String path = File.separator+imgSaveDir+File.separator+saveFile(savePath+File.separator+imgSaveDir,banner);
        b.setBanner(path);
        if(bannerMapper.updateByPrimaryKey(b)>0){
            deleteFile(oldFilePath);
            return 1;
        }
        return 0;
    }

    public int deleteBanner(String savePath, Integer id) {
        Banner b = bannerMapper.selectByPrimaryKey(id);
        String oldFilePath = savePath+b.getBanner();
        if(bannerMapper.deleteByPrimaryKey(id) > 0){
            deleteFile(oldFilePath);
            return 1;
        }
        return 0;
    }


    public List<News> selectNewsPage(Query query) {
        return newsMapper.selectNewsList(query);
    }

    public int totalNewsNum() {
        return newsMapper.totalNum();
    }

    public News selectNewsById(Integer id) {
        return newsMapper.selectByPrimaryKey(id);
    }

    public int insertNews(News news) {
        news.setPostDate(new Date());
        return newsMapper.insert(news);
    }



    public Introduction selectLastIntroduction() {
        return introductionMapper.selectIntroduction();
    }

    public int updateNews(News news) {
        return newsMapper.updateByPrimaryKeySelective(news);
    }

    public int deleteNews(Integer id) {
        return newsMapper.deleteByPrimaryKey(id);
    }

    public int updateIntroductionImage(String savePath, MultipartFile introduction, Integer id) throws IOException {
        Introduction i = introductionMapper.selectByPrimaryKey(id);
        String oldImagePath = savePath+i.getImage();
        String path = File.separator+imgSaveDir+File.separator+saveFile(savePath+File.separator+imgSaveDir,introduction);
        i.setImage(path);
        if(introductionMapper.updateByPrimaryKey(i)>0){
            deleteFile(oldImagePath);
            return 1;
        }
        return 0;
    }

    public int updateIntroductionContent(Introduction introduction) {
        return introductionMapper.updateByPrimaryKeySelective(introduction);
    }

    public List<Member> selectMemberPage(Query query) {

        return memberMapper.selectMemberList(query);
    }

    public int totalMemberNum() {
        return memberMapper.totalNum();
    }

    public Member selectMemberById(Integer id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    public int updateMember(Member member, List<MemberMsg> memberMsgList, String savePath, MultipartFile img) throws IOException {
        //update msg
        String oldImagePath = null;
        member.setImage(null);
        if(img != null && img.getOriginalFilename()!=null&&img.getOriginalFilename().trim().length()>0){
            Member m = memberMapper.selectByPrimaryKey(member.getId());
            oldImagePath = savePath+m.getImage();
            String path = File.separator+imgSaveDir+File.separator+saveFile(savePath+File.separator+imgSaveDir,img);
            member.setImage(path);
        }
        if(memberMapper.updateByPrimaryKeySelective(member)>0){
            if(memberMsgMapper.deleteByMemberId(member.getId()) > 0){
                if(insertMemberMsgList(member.getId(),memberMsgList) == memberMsgList.size()){
                    deleteFile(oldImagePath);
                    return 1;
                }
            }
            throw  new RuntimeException("数据更新异常");
        }
        return 0;
    }

    public List<MemberMsg> selectMemberMsgByMemId(Integer memId) {
        return memberMsgMapper.selectByMemberId(memId);
    }

    public List<SubMenu> selectSubMenuByMenu(String menu) {
        return subMenuMapper.selectSubMenuListByMenu(menu);
    }

    @Transactional
    public int insertMember(Member member, String savePath, MultipartFile img, List<MemberMsg> memberMsgList) throws IOException {
        String path = File.separator+imgSaveDir+File.separator+saveFile(savePath+File.separator+imgSaveDir,img);
        member.setImage(path);
        if(memberMapper.insert(member) > 0){
            if(insertMemberMsgList(member.getId(),memberMsgList) == memberMsgList.size()){
                return 1;
            }
            throw  new RuntimeException("数据添加异常");
        }
        return -1;
    }

    private int insertMemberMsgList(Integer id, List<MemberMsg> memberMsgList) {
        int i = 0;
        for(MemberMsg msg:memberMsgList){
            msg.setMemberId(id);
            if(memberMsgMapper.insert(msg) > 0){
                i+=1;
            }
        }
        return i;
    }

    public int insertPaper(Paper paper) {
        return paperMapper.insert(paper);
    }

    public List<Paper> selectPaperPage(Query query) {
        return paperMapper.selectPaperPage(query);
    }

    public int totalPaperNum() {
        return paperMapper.totalNum();
    }

    public int deletePaper(Integer id) {
        return paperMapper.deleteByPrimaryKey(id);
    }

    public int deleteMember(Integer id, String savePath) {
        //delete msg
        Member member = memberMapper.selectByPrimaryKey(id);
        String oldFilePath = savePath+member.getImage();
        if(memberMsgMapper.deleteByMemberId(id) > 0){
            if(memberMapper.deleteByPrimaryKey(id) > 0){
                deleteFile(oldFilePath);
                return 1;
            }
        }
        return 0;
    }

    public Paper selectPaperById(Integer id) {
        return paperMapper.selectByPrimaryKey(id);
    }

    public int updatePaper(Paper paper) {
        return paperMapper.updateByPrimaryKeySelective(paper);
    }

    public List<Machine> selectMachinePage(Query query) {
        return machineMapper.getMachineList(query);
    }

    public int totalMachineNum() {
        return machineMapper.totalNum();
    }

    public Machine selectMachineById(Integer id) {
        return machineMapper.selectByPrimaryKey(id);
    }

    public int updateMachine(Machine machine, String savePath, MultipartFile img) throws IOException {
        String oldImagePath = null;
        machine.setImage(null);
        if(img != null && img.getOriginalFilename() != null && img.getOriginalFilename().trim().length() > 0){
            Machine m = machineMapper.selectByPrimaryKey(machine.getId());
            oldImagePath = savePath+m.getImage();
            String path = File.separator+imgSaveDir+File.separator+saveFile(savePath+File.separator+imgSaveDir,img);
            machine.setImage(path);
        }
        if(machineMapper.updateByPrimaryKeySelective(machine)>0){
            deleteFile(oldImagePath);
            return 1;
        }
        return 0;
    }

    public int insertMachine(Machine machine, MultipartFile img, String savePath) throws IOException {
        String path = File.separator+imgSaveDir+File.separator+saveFile(savePath+File.separator+imgSaveDir,img);
        machine.setImage(path);
        return machineMapper.insert(machine);
    }

    public List<Research> selectResearchPage(Query query) {
        return researchMapper.selectResearchList(query);
    }

    public int totalResearchNum() {
        return researchMapper.totalNum();
    }

    public int insertResearch(Research research) {
        return researchMapper.insert(research);
    }

    public Research selectResearchById(Integer id) {
        return researchMapper.selectByPrimaryKey(id);
    }

    public int updateResearch(Research research) {
        return researchMapper.updateByPrimaryKeySelective(research);
    }

    public int deleteResearch(Integer id) {
        return researchMapper.deleteByPrimaryKey(id);
    }

    public int deleteMachine(Integer id, String savePath) {
        Machine machine = machineMapper.selectByPrimaryKey(id);
        String oldFilePath = savePath+machine.getImage();
        if(machineMapper.deleteByPrimaryKey(id) > 0){
            deleteFile(oldFilePath);
            return 1;
        }
        return 0;
    }

    public Contact selectContactByMenuId(Integer menuId) {
        return contactMapper.selectContactByMenuId(menuId);
    }

    public int updateContact(Contact contact) {
        return contactMapper.updateByPrimaryKeySelective(contact);
    }
}
